﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;
using MedicalSystem.SamrtReport.Library;

namespace MedicalSystem.SamrtReport
{
    public partial class ComboxBindingSettingFrm : Form
    {
        public ComboxBindingSettingFrm(ComboBox control)
        {
            InitializeComponent();
            this._comboBox = control;
        }

        private ComboBox _comboBox;
        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.ListItemComboBox.Text))
            {
                if (string.IsNullOrEmpty(this.DisplayMemberComboBox.Text))
                {
                    this.DefaultErrorProvider.SetError(this.DisplayMemberComboBox, "请选择列表项要显示的值");
                    return;
                }
                if (string.IsNullOrEmpty(this.ValueMemberComboBox.Text))
                {
                    this.DefaultErrorProvider.SetError(this.ValueMemberComboBox, "请选择列表项实际的值");
                    return;
                }
                ListBoxItem displayItem = this.DisplayMemberComboBox.SelectedItem as ListBoxItem;
                ListBoxItem valueItem = this.ValueMemberComboBox.SelectedItem as ListBoxItem;

                SetControlDataSource(displayItem, valueItem);
            }

            if (this.listBox1.SelectedItem != null)
                SetControlDataBinding(this.listBox1.SelectedItem as ListBoxItem);

            
            this.DialogResult = DialogResult.OK;
        }

        private void SetControlDataBinding(ListBoxItem selectItem)
        {
           
            _comboBox.DataBindings.Clear();
            _comboBox.DataBindings.Add(new Binding(this.BindingToComboBox.Text, dataSource, this.comboBox1.Text + "." + selectItem.Value));
                    
        }

        private void SetControlDataSource(ListBoxItem displayItem, ListBoxItem valueItem)
        {
           
            this._comboBox.DisplayMember = displayItem.Value;
            this._comboBox.ValueMember = valueItem.Value;
          

            StringBuilder xml = new StringBuilder();
            xml.Append("<DataSource name='" + this.ListItemComboBox.Text + "'>");
            for (int i = 0; i < this.RowFilterlistBox.Items.Count; i++)
            {
                xml.Append("<RowFilter>" + this.RowFilterlistBox.Items[i].ToString()+ "</RowFilter>");
            }
            xml.Append("</DataSource>");

            this._comboBox.Tag = xml.ToString();
        }
        private void FDataBindingSetting_Load(object sender, EventArgs e)
        {
            Initalize();

            CustomFormHepler.ShowForm(this);
        }
        private DataSet dataSource = new DataSet();
        private void Initalize()
        {
            string[] files = Directory.GetFiles(BindingData.Path);
            if (files.Length == 0)
            {
                Trace.WriteLine("提示,您当前设计器中无可用数据源,请通过数据源添加向导添加数据源到表单设计器!");
            }
            else
            {
                this.BindingNameComboBox.Items.Clear();

                foreach (string file in files)
                {
                    if (Path.GetExtension(file).ToLower() != ".xml")
                        continue;
                    string fileName = Path.GetFileNameWithoutExtension(file);
                    this.BindingNameComboBox.Items.Add(fileName);
                }

                if (BindingNameComboBox.Items.Count == 0)
                    Trace.WriteLine("提示,您当前设计器中无可用数据源,请通过数据源添加向导添加数据源到表单设计器!");

                if (string.IsNullOrEmpty(BindingData.CurrentBindingSourceName))
                {
                    Trace.WriteLine("提示,请设置当前表单的绑定数据源!");
                    this.BindingNameComboBox.Enabled = true;
                    this.BindingNameComboBox.SelectedIndexChanged += new EventHandler(BindingNameComboBox_SelectedIndexChanged);
                }
                else
                {
                    if (BindingNameComboBox.Items.Contains(BindingData.CurrentBindingSourceName))
                        BindingNameComboBox.Text = BindingData.CurrentBindingSourceName;
                    else
                    {
                        Trace.WriteLine(
                            string.Format("提示,设计器中不存在您当前打开表单的数据源<{0}>,你可以选择其它数据源作为绑定数据源，还可以使用绑定数据源配置向导，添加其它数据源!",
                            BindingData.CurrentBindingSourceName),"Error");
                        this.BindingNameComboBox.Enabled = true;
                        this.BindingNameComboBox.SelectedIndexChanged += new EventHandler(BindingNameComboBox_SelectedIndexChanged);
                    }
                        

                }

                if (!string.IsNullOrEmpty(BindingNameComboBox.Text))
                {
                    LoadDataMember();
                }

            }
            if (this._comboBox.DataBindings.Count > 0)
            {
                string bindingMember = this._comboBox.DataBindings[0].BindingMemberInfo.BindingMember;
                string[] data = bindingMember.Split(new char[] { '.' });

                if (dataSource.Tables.Contains(data[0]))
                {
                    this.comboBox1.Text = data[0];
                    comboBox1_SelectedIndexChanged(comboBox1, EventArgs.Empty);
                    if (dataSource.Tables[comboBox1.Text].Columns.Contains(data[1]))
                    {
                        this.listBox1.SelectedIndex = dataSource.Tables[comboBox1.Text].Columns[data[1]].Ordinal;
                        this.BindingToComboBox.Text = this._comboBox.DataBindings[0].PropertyName;
                    }
                        
                }
                
            }
            else
            {
                if(this.comboBox1.Items.Count>0)
                     this.comboBox1.SelectedIndex = 0;
            }

            if (!string.IsNullOrEmpty(this._comboBox.DisplayMember) 
                && !string.IsNullOrEmpty(this._comboBox.ValueMember) && this._comboBox.Tag!=null)
            {
                string xml = this._comboBox.Tag.ToString();
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xml);
                XmlNode root= xmlDocument.ChildNodes[0];
                string tableName = root.Attributes["name"].Value;

                if (dataSource.Tables.Contains(tableName))
                {
                    this.ListItemComboBox.Text = tableName;
                    ListItemComboBox_SelectedIndexChanged(this.ListItemComboBox, EventArgs.Empty);
                    if (dataSource.Tables[ListItemComboBox.Text].Columns.Contains(this._comboBox.DisplayMember))
                        this.DisplayMemberComboBox.Text = dataSource.Tables[this.ListItemComboBox.Text].Columns[this._comboBox.DisplayMember].Caption;
                    if (dataSource.Tables[ListItemComboBox.Text].Columns.Contains(this._comboBox.ValueMember))
                        this.ValueMemberComboBox.Text = dataSource.Tables[this.ListItemComboBox.Text].Columns[this._comboBox.ValueMember].Caption;
                }
                foreach (XmlNode child in root.ChildNodes)
                {
                    this.RowFilterlistBox.Items.Add(child.InnerText);
                }
               
            }
        }
        private void LoadDataMember()
        {
            if (File.Exists(string.Format(@"{0}\{1}.xml", BindingData.Path, BindingNameComboBox.Text)))
            {
                this.comboBox1.Items.Clear();
                dataSource.ReadXmlSchema(string.Format(@"{0}\{1}.xml", BindingData.Path, BindingNameComboBox.Text));

                for (int i = 0; i < dataSource.Tables.Count; i++)
                {
                    this.comboBox1.Items.Add(dataSource.Tables[i].TableName);
                    ListItemComboBox.Items.Add(dataSource.Tables[i].TableName);
                }
            }
            else
            {
                Trace.WriteLine(string.Format("找不到名为<{0}>的数据源!", BindingNameComboBox.Text));
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(comboBox1.Text))
                return;
            this.listBox1.Items.Clear();
            for (int j = 0; j < dataSource.Tables[comboBox1.Text].Columns.Count; j++)
            {
                ListBoxItem item = new ListBoxItem();
                item.Text = dataSource.Tables[comboBox1.Text].Columns[j].Caption;
                item.Value = dataSource.Tables[comboBox1.Text].Columns[j].ColumnName;
                this.listBox1.Items.Add(item);
            }
            this.button1.Enabled = false;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.button1.Enabled = listBox1.SelectedItem != null;
            if(this.listBox1.SelectedItem!=null)
              this.BindingToComboBox.SelectedIndex = 1;

        }

        private void ListItemComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.DisplayMemberComboBox.Items.Clear();
            this.ValueMemberComboBox.Items.Clear();
            this.RowFilterComboBox.Items.Clear();

            if (string.IsNullOrEmpty(ListItemComboBox.Text))
                return;

            for (int j = 0; j < dataSource.Tables[ListItemComboBox.Text].Columns.Count; j++)
            {
                ListBoxItem item = new ListBoxItem();
                item.Text = dataSource.Tables[ListItemComboBox.Text].Columns[j].Caption;
                item.Value = dataSource.Tables[ListItemComboBox.Text].Columns[j].ColumnName;
                if (string.IsNullOrEmpty(item.Text))
                    item.Text = item.Value;
                this.DisplayMemberComboBox.Items.Add(item);
                this.ValueMemberComboBox.Items.Add(item);
                this.RowFilterComboBox.Items.Add(item);
            }

            this.button1.Enabled = true;
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.RowFilterComboBox.Text))
                return;
            ListBoxItem item = this.RowFilterComboBox.SelectedItem as ListBoxItem;
            if (item == null)
                return;
            if (string.IsNullOrEmpty(this.RowFilterTextBox.Text))
            {
                this.DefaultErrorProvider.SetError(this.RowFilterTextBox, "请输入筛选值");
                return;
            }
               
            this.RowFilterlistBox.Items.Add(string.Format("{0}='{1}'", item.Value, this.RowFilterTextBox.Text));
        }

        private void ReduceButton_Click(object sender, EventArgs e)
        {
            if (this.RowFilterlistBox.SelectedItem != null)
                this.RowFilterlistBox.Items.Remove(this.RowFilterlistBox.SelectedItem);
        }

        private void RowFilterComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
           this.AddButton.Enabled = !string.IsNullOrEmpty(this.RowFilterComboBox.Text);
          
        }

        private void RowFilterlistBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ReduceButton.Enabled = this.RowFilterlistBox.SelectedItem != null;
        }

        private void BindingNameComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(BindingNameComboBox.Text))
            {
                if (MessageBox.Show(string.Format("是否确定选择<{0}>作为当前表单的绑定数据源", BindingNameComboBox.Text),
                    "提示框", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    LoadDataMember();
                    BindingNameComboBox.Enabled = false;
                    BindingData.CurrentBindingSourceName = BindingNameComboBox.Text;
                }


            }
        }
    }
}
